<template>
  <div>
    <el-table-form ref="form" :model="query">
      <el-form-item label="车牌号">
        <el-input v-model="query.truckCode" placeholder="请选择" clearable />
      </el-form-item>
      <el-form-item label="所属机构">
        <el-tree-select
          v-model="query.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'default-expand-all': true,
            'expand-on-click-node': false,
            'highlight-current': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
        />
      </el-form-item>
      <el-form-item label="是否启用">
        <el-select v-model="query.truckStatus">
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="2" />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <div>
        <el-button type="primary" icon="el-icon-plus" @click="add">新增</el-button>
        <el-button type="primary" icon="el-icon-folder-opened" @click="exportFile">导出</el-button>
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <add ref="add" :tree-data="treeData" />
  </div>
</template>

<script>
  import { queryTruckManageList, queryEableVehicle, queryExportVehicleList, queryExportDomain } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import Add from './components/AddVehicle'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'

  export default {
    name: 'tab-info',
    components: {
      Add
    },
    data() {
      return {
        exportDomain: '',
        treeData: [],
        query: {
          truckCode: '',
          orgSNNo: '',
          truckStatus: ''
        },
        tableData: {
          total: 0,
          column: [
            {
              prop: 'truckCode',
              label: '车牌号',
              render: (h, { row }) => <el-link onClick={() => this.openDetail(row)}>{row.truckCode}</el-link>
            },
            {
              prop: 'orgName',
              label: '所属机构'
            },
            {
              prop: 'truckType',
              label: '车型'
            },
            {
              prop: 'remark',
              label: '备注'
            },
            {
              prop: 'truckStatus',
              label: '是否启用',
              render: (h, { row }) => <span>{ row.truckStatus === 1 ? '启用' : '禁用' }</span>
            },
            {
              label: '操作',
              align: 'center',
              fixed: 'right',
              width: 100,
              render: (h, { row }) => {
                return (
                  <div>
                    <el-link size='mini' onClick={() => this.update(row)}>编辑</el-link>
                    <el-link size='mini' onClick={() => this.use(row)}>启/禁用</el-link>
                  </div>
                )
              }
            }
          ],
          data: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList'
      ])
    },
    async created() {
      await Promise.all([this.getExportDomain(), this.getTreeData()])
    },
    methods: {
      // 获取导出域名
      getExportDomain() {
        mergeAsyncFunc(queryExportDomain)
          .then((res) => {
            this.exportDomain = res.data
          })
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        const res = await queryTruckManageList(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
      },
      openDetail() {},
      async add() {
        await this.$refs.add.open()
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      async update(row) {
        await this.$refs.add.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 启/禁用
      async use(row) {
        let title = '启用'
        if (row.truckStatus === 1) title = '禁用'
        this.$confirm(`确定${title}该辆车`, '提示', {
          type: 'warning'
        }).then(() => {
          const loading = this.$message({
            message: '正在执行操作',
            duration: 0,
            iconClass: 'el-icon-loading'
          })
          this.$refs.lbTable.fetch({ currentPage: 1 })
          queryEableVehicle({ truckId: row.truckId }).then(() => {
            this.$refs.lbTable.fetch({ currentPage: 1 })
            this.$notify({
              title: '提示',
              message: `${title}成功`,
              type: 'success',
              duration: 2000
            })
          }).finally(() => {
            loading.close()
          })
        })
      },
      // 导出
      async exportFile() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'info'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.tableData.column))
          copyColumn.pop()
          const str = {}
          copyColumn.forEach(item => {
            str[item.prop] = item.label
          })
          queryExportVehicleList({
            paramInfo: _this._getQuery(_this.query),
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      reset() {
        this.$refs.form.resetFields()
      }
    }
  }
</script>

<style scoped>

</style>
